import { defineStore } from 'pinia'
import { getStore, setStore } from '../../utils/store'
import config from '../../config'
import routeList from '../../mock/routes'

interface state {
  themeColor: string,
  windowWidth: number,
  sidebarShrink: boolean,
  sidebarWidth: number,
  sidebarOption: {
    width: number[],
    miniWindowShrink?: number,
  },
  background: string,
  routeList: any,
  navigation: {
    active: number,
    list: any[],
  },
  userInfo: any,
}
const useCommonStore = defineStore({
  id: 'common',
  state: ():state => ({
    themeColor: 'red', // 主题色
    windowWidth: 0, // 当前窗口宽度
    sidebarShrink: false, // 是否收缩侧边栏
    sidebarWidth: 240, // 当前侧边栏宽度
    sidebarOption: {
      width: [240, 60], // 展开和收缩的宽度
      miniWindowShrink: 1024, // 窗口小于1024像素自动收缩
    },
    background: '#20222a',
    routeList: [],
    // navigation
    navigation: {
      active: 0,
      list: [],
    },
    userInfo: {
      name: 'admin',
    }, // 用户信息
  }),
  actions: {
    // 设置侧边栏收缩
    setSidebarShrink(shrink: boolean) {
      this.sidebarShrink = shrink
      const widthOption = this.sidebarOption.width
      this.sidebarWidth = shrink ? widthOption[1] : widthOption[0]
    },
    getRouteList() {
      this.routeList = routeList
    },
    // 对颜色进行处理
    setStoreColor(color: string) {
      this.themeColor = color
      this.appendColorToHead(color)
      setStore(`${ config.siteStoreKey }_themeColor`, color)
    },
    getStoreColor() {
      const color = getStore(`${ config.siteStoreKey }_themeColor`) || config.themeColor
      this.appendColorToHead(color)
      this.themeColor = color
      return color
    },
    // style添加到head
    appendColorToHead(color: string) {
      document.querySelector('#_themeColor')?.remove()
      const styleEl = `
        .el-menu-item.is-active .__active-left {
          background-color: ${ color };
        }
      `
      const style = document.createElement('style')
      style.id = '_themeColor'
      style.innerHTML = styleEl
      document.head.appendChild(style)
    },
  },
})

export default useCommonStore
